<!DOCTYPE html>
<script src="../../resources/testharness.js"></script>
<script src="../../resources/testharnessreport.js"></script>
<body>
<script>
  /************************************************************************
   *   Helper functions!
   */
  function createFrame(markup) {
    var i = document.createElement('iframe');
    i.srcdoc = markup;
    return i;
  }

  function appendAndWaitForLoad(test, frame) {
    return new Promise((resolve, reject) => {
      frame.onload = test.step_func(_ => {
        frame.onload = null;
        resolve();
      });
      document.body.appendChild(frame);
    });
  }

  function assert_select(test, frame, value) {
    var select = frame.contentDocument.querySelector('select');
    assert_equals(select.value, value, 'select');
  }

  function assert_element_innerText(test, frame, name, value) {
    var el = frame.contentDocument.querySelector(name);
    if (value === null || value === undefined)
      assert_equals(el, null, name);
    else
      assert_equals(el.innerText, value, name);
  }

  /************************************************************************
   *   The actual tests!
   */
  var tests = [
    // <input>, <keygen>, and <textarea> close <select>, so <plaintext> works.
  ];

  var elementsToIgnore = [
    "iframe",
    "noembed",
    "noframes",
    "noscript",
    "plaintext",
    "style",
    "xmp",
  ];

  elementsToIgnore.forEach(el => {
    tests.push(
      {
        markup: `<form><select><option><${el}>1<element></element>`,
        select: "1",
        innerText: null,
        name: el
      }, {
        markup: `<form><select><option>1<${el}>2<element></element>`,
        select: "12",
        innerText: null,
        name: el
      }, {
        markup: `<form><select><option>1<${el}>2<element></element>3`,
        select: "123",
        innerText: null,
        name: el
      });
    if (el != "iframe") {
      tests.push(
        {
          markup: `<form><select><option>1<input><${el}>2<element></element>`,
          select: "1",
          innerText: "2<element></element>",
          name: el
        }, {
          markup: `<form><select><option>1<keygen><${el}>2<element></element>`,
          select: "1",
          innerText: "2<element></element>",
          name: el
        }, {
          markup: `<form><select><option>1<textarea></textarea><${el}>2<element></element>`,
          select: "1",
          innerText: "2<element></element>",
          name: el
        });
    }
  });
  

  tests.forEach(test => {
    async_test(t => {
      var i = createFrame(test.markup);

      appendAndWaitForLoad(t, i)
        .then(t.step_func_done(_ => {
          assert_select(t, i, test.select);
          assert_element_innerText(t, i, test.name, test.innerText);
        }));
    }, test.markup);
  });
</script>
